package com.yutian.example.demo.common.vo;

import com.google.common.collect.Maps;
import com.yutian.example.demo.common.utils.ThreadContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

@Data
@Slf4j
public class HttpResponse {

    public static final int AUTH_ERROR_STATUS = 401;

    public static final int ACCESS_ERROR_STATUS = 403;

    public static final int CODE_AUTH_ERROR = 40101;

    public static final int CODE_ACCESS_ERROR = 40301;

    public static final int CODE_NETWORK_ERROR = 400500;

    public static final int CODE_SUCCESS = 0;

    public static final int CODE_FAIL_COMMON = 1;

    public static final int CODE_FAIL_PARAM = 2;



    /**
     *  0表示成功；其它表示失败。注：失败时，不要根据code判断失败类型，它目前只表示失败。
     */
    private int code;
    private String msg;
    private Object data;
    private String logId;

    public HttpResponse(int code, String msg, Object data, String logId) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        if(StringUtils.isBlank(logId)) {
            logId = ThreadContext.getLog();
        }
        this.logId = logId;
    }

    public static HttpResponse createSuc(Object data){
        return createSuc(data, null);
    }

    public static HttpResponse createSuc(Object data, String msg){
        return new HttpResponse(HttpResponse.CODE_SUCCESS, msg, data, null);
    }


    public static HttpResponse createFail(String msg){
        return createFail(HttpResponse.CODE_FAIL_COMMON, msg, null);
    }

    public static HttpResponse createFail(String msg, Object data){
        return createFail(HttpResponse.CODE_FAIL_COMMON, msg, data);
    }

    public static HttpResponse createFail(int code, String msg){
        return createFail(code, msg, null);
    }

    public static HttpResponse createFail(int code, String msg, Object data){
        return new HttpResponse(code, msg, data, null);
    }

    public Map<String, Object> toMap(){
        Map<String, Object> res = Maps.newHashMap();
        res.put("code", code);
        res.put("msg", msg);
        res.put("data", data);
        res.put("logId", logId);
        return res;
    }

}